﻿using AiXiu.Common;
using AiXiu.IDAL;
using AiXiu.Model;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AiXiu.DAL
{
    public class UserService : IUserService
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns>成功true  失败false</returns>
        public bool AddUser(TBLogins tBLogins)
        {
            AiXiuModel db = new AiXiuModel();
            db.TBLogins.Add(tBLogins);
            int result = db.SaveChanges();
            if (result > 0)
            {
                TBUsers tBUsers = new TBUsers()
                {
                    //构建tBUsers表
                    CreationTime = DateTime.Now,
                    Id = tBLogins.Id,
                    Sex = 0
                };
                db.TBUsers.Add(tBUsers);
                return db.SaveChanges() > 0;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据手机号判断用户是否为空
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <returns></returns>
        public bool IsSanmeMobile(string mobile)
        {
            AiXiuModel db = new AiXiuModel();
            var model = db.TBLogins.SingleOrDefault(e => e.MobileNumber == mobile);
            if (model != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 根据用户名判断用户是否为空
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public bool IsSanmeUserName(string userName)
        {
            AiXiuModel db = new AiXiuModel();
            var model = db.TBLogins.SingleOrDefault(e => e.UserName == userName);
            if (model != null)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 通过用户名查找用户信息
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <returns></returns>
        public TBLogins FindByUserName(string userName)
        {
            AiXiuModel db = new AiXiuModel();
            //SingleOrDefault()返回序列中指定条件的唯一元素，如果这样元素不存在则返回默认值
            TBLogins logins = db.TBLogins.SingleOrDefault(m => m.UserName == userName);
            return logins;
        }

        /// <summary>
        /// 通过用户编号（id）查找用户
        /// </summary>
        /// <param name="userId">编号</param>
        /// <returns></returns>
        public TBUsers FindByUserId(int userId)
        {
            AiXiuModel db = new AiXiuModel();
            return db.TBUsers.Find(userId);
        }

        /// <summary>
        /// 通过用户手机号查找用户信息
        /// </summary>
        /// <param name="Mobile">手机号</param>
        /// <returns></returns>
        public TBLogins FindByMobile(string Mobile)
        {
            AiXiuModel db = new AiXiuModel();
            return db.TBLogins.SingleOrDefault(e => e.MobileNumber == Mobile);
        }

        /// <summary>
        /// 更新用户信息（不包含头像）
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public TBUsers EditwithoutAvatar(TBUsers profile)
        {
            AiXiuModel aiXiuModel = new AiXiuModel();
            TBUsers tBUsers = aiXiuModel.TBUsers.SingleOrDefault(e => e.Id == profile.Id);
            if (tBUsers != null)
            {
                tBUsers.NickName = profile.NickName;
                tBUsers.Sex = profile.Sex;
                tBUsers.Birthday = profile.Birthday;
                tBUsers.Address = profile.Address;
                tBUsers.Hobby = profile.Hobby;
                //更新到数据库
                try
                {
                    aiXiuModel.Entry(tBUsers).State = EntityState.Modified;
                    aiXiuModel.SaveChanges();
                }
                catch (Exception ex)
                {

                }
                //返回结果
                return tBUsers;
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 更新用户头像
        /// </summary>
        /// <param name="profile"></param>
        /// <returns></returns>
        public TBUsers EditAvatar(TBUsers profile)
        {
            //查询数据库
            AiXiuModel aiXiuModel = new AiXiuModel();
            TBUsers tBUsers = aiXiuModel.TBUsers.SingleOrDefault(e => e.Id == profile.Id);
            if (tBUsers == null)
            {
                return null;
            }
            tBUsers.Avatar = profile.Avatar;
            //更新到数据库
            aiXiuModel.Entry(tBUsers).State = EntityState.Modified;
            aiXiuModel.SaveChanges();
            //返回结果
            return tBUsers;
        }

        /// <summary>
        /// 待上传视频
        /// </summary>
        /// <param name="videoId">视频Id</param>
        /// <param name="userId">用户Id</param>
        /// <param name="headline">标题</param>
        /// <param name="location">位置</param>
        /// <returns></returns>
        public TBVideos TOBeUpload(string videoId, int userId, string headline, string location = null)
        {
            //实例化AiXiuModel数据库
            AiXiuModel db = new AiXiuModel();
            //实例化TBVideos表
            TBVideos tBVideos = new TBVideos();
            //保存到数据库
            tBVideos.VideoId = videoId;
            tBVideos.UserId = userId;
            tBVideos.Headline = headline;
            tBVideos.Location = location;
            tBVideos.Status = (int)VideoStatus.Uploading;
            tBVideos.UploadTime = DateTime.Now;
            //把数据添加到数据库
            db.Entry(tBVideos).State = EntityState.Added;
            //保存
            db.SaveChanges();
            //返回结果
            return tBVideos;
        }

        /// <summary>
        /// 获取处理中的视频I的列表
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public List<string> GetInProcessVideoIds()
        {
            //实例化List<int>集合
            List<int> queryStatus = new List<int>()
            {
                //上传中
                (int)VideoStatus.Uploading,
                //上传成功
                (int)VideoStatus.UploadSucces,
                //转码中
                (int)VideoStatus.Transcoding
            };
            AiXiuModel db = new AiXiuModel();
            //查询
            return db.TBVideos.Where(m => queryStatus.Contains(m.Status)).Select(m => m.VideoId).ToList();
        }

        /// <summary>
        /// 批量更新视频信息
        /// </summary>
        /// <param name="videoInfos"></param>
        public void UpdateVideos(List<VideoInfo> videoInfos)
        {
            AiXiuModel db = new AiXiuModel();
            foreach (VideoInfo videoInfo in     videoInfos)
            {
                TBVideos tBVideos = db.TBVideos.SingleOrDefault(m => m.VideoId == videoInfo.VideoId);
                tBVideos.Status = (int)videoInfo.Status;
                if (!string.IsNullOrEmpty(videoInfo.CoverURL))
                { 
                    int lastInsex = videoInfo.CoverURL.IndexOf('?');
                    tBVideos.CoverURL = videoInfo.CoverURL.Substring(0, lastInsex);
                }
                db.Entry(tBVideos).State = EntityState.Modified;
                db.SaveChanges();
            }
        }

        /// <summary>
        /// 通过用户id获取视频列表
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <returns></returns>
        public List<TBVideos> GetTBVideosByUserId(int userId)
        {
            AiXiuModel db = new AiXiuModel();
            List<TBVideos> tBVideos = db.TBVideos
                //根据用户ld查找——Where()
                .Where(m => m.UserId == userId)
                //按时间倒序排列―—OrderByDescending()
                .OrderByDescending(m => m.UploadTime)
                .ToList();
            return tBVideos;
        }

        /// <summary>
        /// 根据视频id删除视频
        /// </summary>
        /// <param name="videoid">视频id</param>
        public void DeleteVideo(string videoid)
        {
            AiXiuModel db = new AiXiuModel();
            //1
            TBVideos tBVideos = db.TBVideos.Find(videoid);
            //2
            //TBVideos tBVideos = db.TBVideos.SingleOrDefault(m => videoid==videoid);
            db.TBVideos.Remove(tBVideos);
            db.SaveChanges();
        }

        /// <summary>
        /// 查询可播放视频列表
        /// </summary>
        /// <returns></returns>
        public List<TBVideos> GetVideos()
        {
            AiXiuModel aiXiuModel = new AiXiuModel();
            int statusValue = (int)VideoStatus.Normal; //获取视频状态
            return aiXiuModel.TBVideos.Where(t => t.Status == statusValue) //通过状态查询视频信息
                .Include(t => t.TBUsers)
                .OrderByDescending((t) => t.UploadTime) //连接查询用户信息表
                .ToList();
        }

        /// <summary>
        /// 通过视频id获取视频信息
        /// </summary>
        /// <param name="videoId">视频id</param>
        /// <returns>本地数据库视频信息</returns> 
        public TBVideos GetVideoByVideoId(string videoId)
        {
            AiXiuModel aiXiuModel  = new AiXiuModel();
            TBVideos tBVideos = aiXiuModel.TBVideos
                .Include(m => m.TBUsers)
                .SingleOrDefault(m => m.VideoId == videoId);
            return tBVideos;
        }

        /// <summary>
        /// 获取视频播放凭证
        /// </summary>
        /// <param name="videoId">视频id</param>
        /// <returns>阿里云视频信息</returns>
        public GetPlayInfoResult GetPlayInfo(string videoId)
        {
            //调用VodHelper中【获取视频播放凭证】的方法，返回视频播放地址结果类
            VodHelper vodHelper = new VodHelper();
            return vodHelper.GetPlayInfo(videoId); 
        }
    }
}
